/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sgs.dao;

import br.com.sgs.entity.Departamento;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;

/**
 *
 * @author Eric
 */

public class DAODepartamento extends AbstractDAO implements IDAODepartamento {
    
    public DAODepartamento(){
        super();
    }
    
    @Override
    public Departamento findDepartamentoById(int iddepartamento) {
        try {

            Query q = em.createQuery("SELECT d FROM Departamento d WHERE d.id = :iddepartamento");
            q.setParameter("iddepartamento", iddepartamento);
            
            return (Departamento) q.getSingleResult();

        } catch (Exception e) {
            System.err.println("Erro no findDepartamentoById");
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Departamento> findDepartamentoByAll(String descricao, String ramal, Date dtcriacaoini, Date dtcriacaofin, List<String> lsstatus) {
        try {

            StringBuilder sql = new StringBuilder();

            if (!descricao.equals("")) {
                sql.append("  AND UPPER(d.descricao) LIKE '%").append(descricao.toUpperCase()).append("%'");
            }
            
            if (!ramal.equals("")) {
                sql.append("  AND UPPER(d.ramal) LIKE '%").append(ramal.toUpperCase()).append("%'");
            }

            if (dtcriacaoini != null && dtcriacaofin != null) {
                sql.append(" AND d.dtcriacao BETWEEN :dtcriacaoini AND :dtcriacaofin ");
            }

            if (!lsstatus.isEmpty()) {
                String status = "";
                for (String st : lsstatus) {
                    status += st + ",";
                }
                status += lsstatus.get(0).toString();
                sql.append(" AND d.status  IN (").append(status).append(")");
            }

            Query q = em.createQuery("SELECT d FROM Departamento d WHERE d.id > 0 " + sql.toString() + " ORDER BY d.descricao ASC");

            if (dtcriacaoini != null && dtcriacaofin != null) {
                q.setParameter("dtcriacaoini", dtcriacaoini);
                q.setParameter("dtcriacaofin", dtcriacaofin);
            }

            return q.getResultList();

        } catch (Exception e) {
            System.err.println("Erro na consulta findDepartamentoByAll");
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public List<Departamento> findDepartamento() {
        try {

            Query q = em.createQuery("SELECT d FROM Departamento d");
      
            return q.getResultList();

        } catch (Exception e) {
            System.err.println("Erro no findDepartamento");
            e.printStackTrace();
            return null;
        }
    }
}
